package com.zlp.spring.tx.service.v1.service;

import com.zlp.spring.tx.service.v1.mapper.UserMapper;
import com.zlp.spring.tx.service.v1.util.TransactionalUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.TransactionStatus;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;
import java.util.Map;
import java.util.UUID;

@Service
public class UserService {

    @Autowired
    private UserMapper userMapper;

    @Autowired
    private TransactionalUtils transactionalUtils;

    public UserService(){
        System.out.println("non param constructor");

    }

    public UserService(UserMapper userMapper){
        this.userMapper = userMapper;
    }



    public List<Map<String,Object>> getUserList(){

        List<Map<String, Object>> users = userMapper.getUsers();
        System.out.println(users);
        return users;
    }

    @Transactional
    public void addUser(){
        System.out.println("addUser");
        String username = "testName";
        String password = UUID.randomUUID().toString();
        userMapper.addUser(username,password);
        int i = 1/ 0;
    }

    public void addUser1(int index){
        System.out.println("addUser1");
        TransactionStatus transactionStatus = transactionalUtils.beginTransaction();
        try {
            String username = "testName";
            String password = UUID.randomUUID().toString();
            userMapper.addUser(username,password);
            int i = 1 / index;
            transactionalUtils.commit(transactionStatus);
        }catch (Exception e){
            e.printStackTrace();
            transactionalUtils.rollback(transactionStatus);
        }
    }

    public void addUser2(int index){

        String username = "testName2";
        String password = UUID.randomUUID().toString();
        userMapper.addUser(username,password);
        int i = 1 / index;
    }


}
